package com.text.mqtt_text.mqtt;

import okhttp3.*;
import org.json.JSONObject;
import java.util.concurrent.TimeUnit;

import java.io.*;


/**
 * 需要添加依赖
 * <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
 * <dependency>
 *     <groupId>com.squareup.okhttp3</groupId>
 *     <artifactId>okhttp</artifactId>
 *     <version>4.12.0</version>
 * </dependency>
 */

class Sample {
    public static final String API_KEY = "yfcFVbmxdf5YbKLzN6kBL8AK";
    public static final String SECRET_KEY = "DN57SLClq1tNXZeyLoUmwdcEW3GOhsK6";

    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().readTimeout(300, TimeUnit.SECONDS).build();

    public static void main(String []args) throws IOException{
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"text\":\"孩子和我分享了他们和朋友出去玩的经历，去了郑州的博物馆和打羽毛球，都玩得非常开心。虽然他们没有详细描述博物馆的展品和羽毛球的具体情况，但我能感受到他们的愉快心情。在羽毛球活动中，他们打了半个多小时，大家都感到快乐和放松。后来，孩子向我倾诉了他们与同学绝交的伤心事，因为被误会拿了同学的东西。我建议他通过坦诚的对话来解决误会，希望能给予他一些支持和安慰。\"}");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify?charset=UTF-8&access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        System.out.println(response.body().string());

    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

}